import { constantRoutes } from "@/router";
// import { getRouters } from '@/api/menu'
import Layout from "@/layout/index";
import ParentView from "@/components/ParentView";
let getRouters = function() {
  // 模拟接口 权限 数据 列表
  return new Promise((resovle, reject) => {
    resovle({
      data: [
        {
          path: "/example1",
          component: "Layout", // 每一个一级路由组件 都是必须的
          redirect: "/example/table",
          name: "Example1",
          meta: { title: "Example1", icon: "el-icon-s-help" },
          children: [
            // 只有一个孩子路由 不会出现下拉
            {
              path: "table",
              name: "Table",
              component: "table/index", // component 的变量 对应的 是 resolve => require([`@/views/${view}`], resolve);
              meta: { title: "Table", icon: "table" } // 如果 还想继续嵌套 请模仿nested 的 例子
            },
            {
              path: "tree",
              name: "Tree",
              component: "tree/index",
              meta: { title: "Tree", icon: "tree" }
            }
          ]
        }
      ]
    });
  });
};
const permission = {
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes;
      state.routes = constantRoutes.concat(routes);
    }
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          const accessedRoutes = filterAsyncRouter(res.data);
          // accessedRoutes.push({ path: "*", redirect: "/404", hidden: true });
          commit("SET_ROUTES", accessedRoutes);
          resolve(accessedRoutes);
        });
      });
    }
  }
};

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === "Layout") {
        route.component = Layout;
      } else if (route.component === "ParentView") {
        route.component = ParentView;
      } else {
        route.component = loadView(route.component);
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children);
    }
    return true;
  });
}

export const loadView = view => {
  // 路由懒加载
  return resolve => require([`@/views/${view}`], resolve);
};

export default permission;
